/*
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 */

package com.wttech.dzzf.process.service.initilize;

import com.wtkj.vo.dzzf.base.kfwd.CardInfo;
import com.wttech.dzzf.process.dao.DataInitilizingDao;
import com.wttech.dzzf.process.service.base.BaseInfoService;
import javafx.application.Application;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

import static com.wttech.dzzf.process.constant.UserConstants.DEFAULT_PROCESS_NUM;

/**
 * @author MaShibo
 * @date 2017/12/13.
 */
@Service
public class SubFundAccountProcessService {

	private static final Logger LOGGER = LoggerFactory.getLogger(SubFundAccountProcessService.class);

	private static final String[] TABLES = new String[]{"BS_VEHICLE", "BS_CARD", "BS_OBU"};

	@Resource
	private DataInitilizingDao dataInitilizingDao;

	@Resource
	private SubCardInfoProcesssService subCardInfoProcesssService;

	@Resource
	private BaseInfoService baseInfoService;

	@Resource
	private ThreadPoolTaskExecutor executor;

	private Integer selectValue;

	private boolean isRunning = false;


	private void process() {
		if (selectValue == null) {
			LOGGER.info("请先选择要生成第几阶段的数据");
			return;
		}
		LOGGER.info("正在查询待处理资金账户总数量");
		int total = dataInitilizingDao.queryFundAccountTotalNum();
		LOGGER.info("共{}条资金账户信息待处理", total);
		int perNum = total / 3;
		LOGGER.info("每个阶段约处理{}条数据", perNum);
		int startTotalRow = (selectValue - 1) * perNum + 1;
		int endTotalRow = selectValue * perNum;
		if (endTotalRow > total) {
			endTotalRow = total;
		}
		LOGGER.info("已选择处理第{}阶段数据", selectValue);
		LOGGER.info("起始总行号【{}】，终止总行号【{}】", startTotalRow, endTotalRow);
		int perTotal = endTotalRow - startTotalRow + 1;
		LOGGER.info("该阶段要处理{}条数据", perTotal);
		int count = (int) Math.ceil((double) perTotal / DEFAULT_PROCESS_NUM);
		LOGGER.info("该阶段每个线程处理每次处理{}条数据，共需要处理{}次", DEFAULT_PROCESS_NUM, count);
		List<Future<Void>> futures = new ArrayList<>(count);
		for (int i = 0; i < count; i++) {
			int startRow = startTotalRow + DEFAULT_PROCESS_NUM * i;
			int endRow = startTotalRow + DEFAULT_PROCESS_NUM * (i + 1) - 1;
			int finalEndRow = endRow > endTotalRow ? endTotalRow : endRow;
			futures.add(executor.submit(() -> {
				processOnce(startRow, finalEndRow);
				return null;
			}));
		}
		baseInfoService.getFutureResult(futures);
		LOGGER.info("数据处理完毕");
		executor.shutdown();
	}

	private void processOnce(int startRow, int endRow) {
		LOGGER.info("开始处理，第【{}】行至第【{}】行的数据", startRow, endRow);
		List<String> funAccountIds = dataInitilizingDao.queryFundAccountIdByRow(startRow, endRow);
		funAccountIds.forEach(funAccountId -> {
			List<CardInfo> cardInfos = dataInitilizingDao.queryCardInfosByFundAccountId(funAccountId);
			cardInfos.forEach(this::processCardInfo);
		});
		LOGGER.info("第【{}】行至第【{}】行的数据，处理完成", startRow, endRow);
	}

	private void processCardInfo(CardInfo cardInfo) {
		try {
			subCardInfoProcesssService.processCardInfo(cardInfo);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
	}

	@Scheduled(fixedDelay = 1000 * 60)
	public void moitor() {
		if (!isRunning) {
			return;
		}
		baseInfoService.buildMonitorMsg(TABLES);
	}

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		SubFundAccountProcessService service = context.getBean(SubFundAccountProcessService.class);
		service.isRunning = true;
		service.selectValue = Integer.valueOf(args[0]);
		service.process();
	}

}
